﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using umbraco.cms.businesslogic.web;

namespace CodeGecko.Umbraco.DataTypes.Umb45x {
    internal static class Helper {

        public static void GetDocumentTypesByParent(int masterDoctypeId, ref List<DocumentType> list)
        {
            GetDocumentTypesByParent(masterDoctypeId, true, true, ref list);
        }

        public static void GetDocumentTypesByParent(int masterDoctypeId, bool recursive, bool includeMaster, ref List<DocumentType> list)
        {
            List<DocumentType> dtAll = DocumentType.GetAllAsList();
            List<DocumentType> dt = new List<DocumentType>();
            foreach (DocumentType dta in dtAll)
            {
                if (dta.MasterContentType == masterDoctypeId)
                {
                    list.Add(dta);
                    dt.Add(dta);
                }
            }

            foreach (DocumentType dta in dt)
            {
                GetDocumentTypesByParent(dta.Id, ref list);
            }
            //Don't forget to include the original doctype too!
            if (includeMaster)
            {
                bool found = false;
                foreach (DocumentType dta in list)
                {
                    if (dta.Id == masterDoctypeId) found = true;
                }
                if (!found) list.Add(new DocumentType(masterDoctypeId));
            }
        }

        internal static string DocumentTypesAsString(int masterDoctypeId, bool recursive)
        {
            return DocumentTypesAsString(masterDoctypeId, recursive, true);
        }

        internal static string DocumentTypesAsString(int masterDoctypeId, bool recursive, bool includeMaster)
        {
            List<DocumentType> dt = new List<DocumentType>();
            GetDocumentTypesByParent(masterDoctypeId, ref dt);
            string retVal = string.Empty;
            string formatRet = "SELECT '{0}' AS Alias";
            string union = " UNION ALL ";
            foreach (DocumentType d in dt)
            {
                retVal += string.Format(formatRet, d.Alias);
                if (dt.IndexOf(d) != (dt.Count - 1)) retVal += union;
            }
            return retVal;
        }

    }
}